package com.baselib;

import java.text.DecimalFormat;

/**
 * script Name: Message.java
 * @author 	Zhikun Cai @ Thomson Beijing office
 * @version	1.0
 * function:	Data model for socket message communication,
 *		including message protocol head,serial number as head,body.
 * @see message.py
 * date:	2008-09-17
 * update date:  
 * update item:  
 */

public final class Message {

	private String head;
	private String body;
	private int serialNumber;
	
	
	/**
	 * @return the body
	 */
	public String getBody() {
		return body;
	}
	
	/**
	 * @param body the body to set
	 */
	public void setBody(String body) {
		this.body = body;
	}
	
	/**
	 * @return the head
	 */
	public String getHead() {
		return head;
	}
	
	/**
	 * @return the serialNumber
	 */
	public int getSerialNumber() {
		return serialNumber;
	}
	
	/**
	 * This function is also the setting of head.
	 * @param serialNumber the serialNumber to set
	 */
	public void setSerialNumber(int serialNumber) {
		this.serialNumber = serialNumber;
		this.head = String.valueOf(serialNumber);
	}
	
	/**
	 * @return length of (String)serial number.
	 */
	public int getHeadLength() {
		return head.length();
	}
	
	/**
	 * @return length of message body.
	 */
	public int getBodyLength() {
		return body.length();
	}
	
	/**
	 * return the whole message string made of protocol head, 
	 * serial number head and body.
	 * @return the whole message string
	 */
	public String buildMsgBuf() {
		/*
		String buf = len2Str(getHeadLength()) + 
					 len2Str(getBodyLength()) +
					 head + body;
					 */
		DecimalFormat df = new DecimalFormat();
		String pattern = "#00000000";
		df.applyPattern(pattern);
		String buf = df.format(body.length())+body;
		return buf;
	}
	
	/**
	 * convert int to String.
	 * @param length
	 * @return String
	 */
	private String len2Str(int length) {
		String str = String.valueOf(length);
		if (str.length() > 8) {
			System.err.println("Error in message: str is too long when converting to int!");
			System.exit(-1);
		}
		while (str.length() < 8)
			str = '0' + str;
		return str;
	}
}
